package com.jwetherell.my.problems.misc;

public class CircularQueue2 {

	private Integer[] queue = null;
	private int size;
	private int head = 0;
	private int tail = 0;

	public CircularQueue2(int size) {
		if (size < 0)
			throw new IllegalArgumentException("Legnth should be >= 0");

		this.size = size;
		this.queue = new Integer[size];
	}

	public synchronized boolean enqueue(Integer data) {
		int index = (head < size) ? head : (head % size);
		tail += ((head - tail) == size) ? 1 : 0;
		queue[index] = data;
		head++;
		return (true);
	}

	public synchronized Integer dequeue() {
		if (queue == null || (head - tail) == 0)
			return (null);
		int index = (tail < size) ? tail : (tail % size);
		Integer value = queue[index];
		tail++;
		return (value);
	}
}